<template>
  <div>
    <PageDialog
      :title="dialogInfo.title"
      v-model:visible="shows"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="dialog-table">
        <PageFilter
          v-model:query="filterInfo.query"
          :filter-list="filterInfo.list"
        >
          <template v-slot:filter-button>
            <div>
              <div class="dialog-table-header">
                <div class="header-left">
                  <div class="lable">产品名称：{{ info.commonName }}</div>
                  <div class="lable">生产批号：{{ info.batchNumber }}</div>
                </div>
                <div class="header-right">
                  <div class="scan-groups">
                    <el-input
                      v-model="filterInfo.keyword"
                      :clearable="true"
                      placeholder="请输入个体码"
                      @keyup.enter.native="search"
                      @input="(e) => (filterInfo.keyword = validSe(e))"
                    ></el-input>
                    <el-button style="margin-left: 10px" @click="search"
                      >搜索</el-button
                    >
                  </div>
                </div>
              </div>
              <el-button @click="printQrCode" v-if="status !== 1"
                >打印二维码</el-button
              >
            </div>
          </template>
        </PageFilter>
      </div>
      <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
        <DialogTable
          v-model:data="tableInfo.data"
          :check-box="false"
          :tab-index="true"
          :listen-height="false"
          :pager="false"
          :field-list="tableInfo.fieldList"
          :handle="tableInfo.handle"
        >
        </DialogTable>
      </el-form>
    </PageDialog>
    <ChosePrinter :visible="printerInfo.visible" @callBack="printerCallBack" />
    <page-dialog
      v-if="dialogReInfo.visible"
      :title="dialogReInfo.title"
      v-model:visible="dialogReInfo.visible"
      :width="dialogReInfo.width"
      :bt-loading="dialogReInfo.btLoading"
      :bt-list="dialogReInfo.btList"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        v-model:ref-obj="formInfo.ref"
        :data="formInfo.data"
        :field-list="formInfo.fieldList"
        :label-width="formInfo.labelWidth"
      >
        <template v-slot:form-qty>
          <span>{{ $fn.qtyFormatter(formInfo.data.qty) }}</span>
        </template>
        <template v-slot:form-price>
          <span>{{ formInfo.data.price }}</span>
          <span
            v-if="
              formInfo.data.isLimitPrice == 1 &&
              formInfo.data.price > formInfo.data.purchaseLimitPrice
            "
            style="color: red"
          >
            超过产品限价:{{ formInfo.data.purchaseLimitPrice }}
          </span>
        </template>
        <template v-slot:form-sterilizationNumber>
          <span>{{ formInfo.data.sterilizationNumber }}</span>
        </template>
      </page-form>
      <ScanInputBox
        :query="scanInfo.query"
        :table-data="[formInfo.row]"
        :api="scanInfo.api"
        :get-product-ids="scanInfo.getProductIds"
        @callback="onCallBackScanData"
      />
      <el-form ref="tableForm" :model="dialogTable" style="width: 100%">
        <DialogTable
          v-model:data="dialogTable.data"
          :field-list="dialogTable.fieldList"
          :handle="dialogTable.handle"
          :check-box="false"
          :tab-index="true"
          :pager="false"
          :row-class-name="tableRowClassName"
        >
          <template v-slot:col-qty="scope">
            <el-form-item class="margin-bottom">
              <div class="page-table-input-number-wrapper">
                <div class="page-table-input-number-left">
                  <div class="page-table-input-number-item">
                    <el-form-item>
                      <el-input-number
                        v-model.lazy="scope.row.largeUnitQty"
                        style="width: 100%; margintop: 18px"
                        clearable
                        controls-position="right"
                        :precision="
                          scope.row.qtyOperateMode === 0 ||
                          scope.row.qtyOperateMode === 2
                            ? 0
                            : systemConfig.qty_show_precision
                        "
                        :min="0"
                        :max="largeMax(scope.row)"
                        @change="changeLarge($event, scope.row)"
                      />
                    </el-form-item>
                    <div class="page-table-input-number-item-unite">
                      {{ scope.row.unitName }}
                    </div>
                  </div>
                  <div
                    v-if="
                      scope.row.unitConvertCoefficient > 1 &&
                      scope.row.qtyOperateMode === 2
                    "
                    class="page-table-input-number-item"
                  >
                    <el-form-item>
                      <el-input-number
                        v-model.lazy="scope.row.smallUnitQty"
                        style="width: 100%; margintop: 18px"
                        clearable
                        controls-position="right"
                        :precision="0"
                        :min="0"
                        :max="smallMax(scope.row)"
                        @change="changeSmall($event, scope.row)"
                      />
                    </el-form-item>
                    <div class="page-table-input-number-item-unite">
                      {{ scope.row.calcUnitName }}
                    </div>
                  </div>
                </div>
                <div
                  v-if="scope.row.qtyOperateMode === 2"
                  class="page-table-input-number-right"
                >
                  {{ $fn.qtyFormatter(scope.row.qty) }}
                </div>
              </div>
            </el-form-item>
          </template>
        </DialogTable>
      </el-form>
    </page-dialog>
  </div>
</template>

<script setup name="IndividualDetails">
import {
  deliverOrderDetailAll,
  printQrCodeDeliverOrderDetails,
  deliverOrderReshipment,
  deliverOrderScan,
} from '@/api/supplier.js'
import ScanInputBox from './ScanInputBox'
const selectedScanOptions = ref([
  {
    label: '增加',
    value: '1',
  },
  {
    label: '减少',
    value: '2',
  },
])
const emits = defineEmits()
const store = useStore()
const { proxy } = getCurrentInstance()
const props = defineProps({
  showDialog: {
    type: Boolean,
  },
  pageStatus: {
    type: Boolean,
  },
  tableIndex: {
    type: Number,
    default: 0,
  },

  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  info: {
    type: Object,
    default: function () {
      return {}
    },
  },
  status: {
    type: Number,
  },
  infoListData: {
    type: Object,
    default: function () {
      return {}
    },
  },
  tableData: {
    type: Array,
    default: function () {
      return []
    },
  },
  type: {
    type: String,
    default: '',
  },
})
const systemConfig = ref(store.state.permission.systemConfig)
const selectedScanValue = ref('1')
const scanInput = ref('')
// 过滤相关配置
const filterInfo = ref({
  keyword: '',
  list: [{ type: 'slot', value: 'button' }],
})
// 表格相关
const tableInfo = ref({
  data: [],
  selections: [],
  copyData: [],
  fieldList: [
    { label: '二维码', value: 'qrCode' },
    { label: '个体码', value: 'uniqueCode' },
    { label: '原厂主码', value: 'factoryMainCode' },
    { label: '原厂从码', value: 'factorySubCode' },
    {
      label: '发货数量',
      value: 'qty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: '单价',
      value: 'price',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '150',
    btList: [
      {
        label: '打印二维码',
        event: printQrCode,
        show: props.status !== 1,
      },
      {
        label: '重新发货',
        event: afreshInvoce,
        show:
          props.status == 2 &&
          props.info.codeType === 3 &&
          props.type !== 'pendDealDeliverOrder',
      },
      {
        label: '撤销发货',
        event: revokeInvoce,
        show: true,
        ifRender: ifRenderRevokeValue,
      },
    ],
  },
})
const scanInfo = ref({
  query: {
    saleId: '',
    hospitalId: '',
  },
  api: deliverOrderScan,
  getProductIds: [props.info.productId],
})
const formInfo = ref({
  ref: null,
  data: {},
  row: {},
  oldData: {},
  fieldList: [
    {
      label: '发货数量',
      value: 'qty',
      type: 'slot',
    },
    {
      label: '结算单价',
      value: 'price',
      type: 'slot',
    },
    {
      label: '灭菌批号',
      value: 'sterilizationNumber',
      type: 'slot',
    },
  ],
  labelWidth: '120px',
})
const dialogTable = ref({
  data: [],
  fieldList: [
    {
      label: '发货数量',
      value: 'qty',
      type: 'slot',
    },
    { label: '原厂主码', value: 'factoryMainCode' },
    { label: '原厂从码', value: 'factorySubCode' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '删除',
        event: remove,
        show: true,
      },
    ],
  },
})
const dialogReInfo = ref({
  visible: false,
  title: '重新发货',
  btLoading: false,
  type: '',
  msg: '',
  width: '700px',
  flag: true,
  btList: [
    { label: '关闭', event: handleReClose, show: true },
    {
      label: '保存',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})

// 弹窗相关
const dialogInfo = ref({
  title: '个体详情',
  width: '90%',
  btLoading: false,
  btList: [{ label: '关闭', event: handleClose, show: true }],
})
const printerInfo = ref({
  visible: false,
  data: {},
})
const shows = computed({
  get() {
    return props.showDialog
  },
  set(val) {
    emits('update:showDialog', val) // 更新父组件shows
  },
})

watch(
  () => dialogTable.value.data,
  () => {
    if (dialogTable.value.data.length) {
      let calcQty = 0
      let largeUnitQty = 0
      let smallUnitQty = 0
      dialogTable.value.data.forEach((row) => {
        let smallUnitQty1 = parseFloat(row.smallUnitQty || 0)
        let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
        let largeUnitQty1 = parseFloat(row.largeUnitQty || 0)
        let calcQty1 = proxy.$fn.accAdd(
          proxy.$fn.accMul(largeUnitQty1, unitConvertCoefficient),
          smallUnitQty1
        )

        let qty = proxy.$fn.accDiv(calcQty1, unitConvertCoefficient)
        let sumAmount = proxy.$fn.accMul(row.qty, row.price || 0)
        row.calcQty = calcQty1
        row.qty = qty
        row.sumAmount = sumAmount
        calcQty = proxy.$fn.accAdd(row.calcQty, calcQty)
        largeUnitQty = proxy.$fn.accAdd(row.largeUnitQty, largeUnitQty)
        smallUnitQty = proxy.$fn.accAdd(row.smallUnitQty, smallUnitQty)
      })
      formInfo.value.row.calcQty = calcQty
      formInfo.value.row.largeUnitQty = largeUnitQty
      formInfo.value.row.smallUnitQty = smallUnitQty
      formInfo.value.row.qty = proxy.$fn.accDiv(
        calcQty,
        formInfo.value.row.unitConvertCoefficient
      )
    } else {
      formInfo.value.row.calcQty = 0
      formInfo.value.row.largeUnitQty = 0
      formInfo.value.row.smallUnitQty = 0
      formInfo.value.row.qty = 0
    }
  },
  {
    deep: true,
  }
)
function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    if (row.codeType === 3) {
      return 1
    }
    return parseInt(row.deliverableCalcQty / row.unitConvertCoefficient)
  } else {
    if (row.codeType === 3) {
      return 1
    }
    return row.deliverableQty
  }
}
function changeSmall(e, row) {
  let item = dialogTable.value.data.find(
    (item) => item.tableIndex === row.tableIndex
  )
  item.smallUnitQty = e
  if (row.codeType === 3 && row.qtyOperateMode === 2) {
    if (e > 0) {
      row.largeUnitQty = 0
      item.largeUnitQty = 0
    }
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(
    row.deliverableCalcQty / row.unitConvertCoefficient
  )
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.deliverableCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row) {
  let item = dialogTable.value.data.details.find(
    (item) => item.tableIndex === row.tableIndex
  )
  item.largeUnitQty = e
  if (row.codeType === 3) {
    if (e === 1) {
      row.smallUnitQty = 0
      item.smallUnitQty = 0
    }
  } else {
    let largeUnitQty = parseInt(
      row.deliverableCalcQty / row.unitConvertCoefficient
    )
    if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
      if (largeUnitQty > 0 && e === largeUnitQty) {
        let smallUnitQty = parseInt(
          row.deliverableCalcQty % row.unitConvertCoefficient
        )
        if (row.smallUnitQty > smallUnitQty) {
          row.smallUnitQty = smallUnitQty
          item.smallUnitQty = smallUnitQty
        }
      }
    }
  }
}
function ifRenderRevokeValue() {
  return (
    tableInfo.value.copyData.length > 1 &&
    props.status == 2 &&
    (props.info.codeType === 2 || props.info.codeType === 3) &&
    props.type !== 'pendDealDeliverOrder'
  )
}
function afreshInvoce(row) {
  //重新发货
  let info = proxy.$fn.deepClone(props.info)
  dialogReInfo.value.visible = true
  formInfo.value.oldData = proxy.$fn.deepClone(row)
  formInfo.value.row = info
  formInfo.value.data.qty = 0
  formInfo.value.data.price = info.price
  formInfo.value.data.sterilizationNumber = info.sterilizationNumber
  formInfo.value.row.details = []
  scanInfo.value.query.saleId = props.infoListData.saleId
  scanInfo.value.query.deliverId = props.infoListData.id
  scanInfo.value.query.hospitalId = props.infoListData.hospitalId
  scanInfo.value.getProductIds = [props.info.productId]
}
function remove(row) {
  dialogTable.value.data = dialogTable.value.data.filter((item) => item != row)
  formInfo.value.row.details = formInfo.value.row.details.filter(
    (item) => item != row
  )
  formInfo.value.row.flag = false
}
function revokeInvoce(data) {
  //撤销发货
  let details = proxy.$fn.deepClone(tableInfo.value.data)
  details = details.filter((item) => item.id !== data.id)
  let row = proxy.$fn.deepClone(props.info)
  row.details = details
  let mergeDetails = proxy.$fn.deepClone(props.tableData)
  mergeDetails[props.tableIndex] = row
  const prarms = {
    ...proxy.$fn.deepClone(props.infoListData),
    mergeDetails: mergeDetails,
  }
  deliverOrderReshipment(prarms).then((res) => {
    if (res && res.success) {
      handleReClose()
      emits('reset')
      shows.value = false
    }
  })
}
function handleReClose() {
  dialogReInfo.value.visible = false
  formInfo.value.data = {}
  formInfo.value.oldData = {}
  formInfo.value.row = {}
  dialogTable.value.data = []
}
function checkConfirm() {
  formInfo.value.row.details = dialogTable.value.data
  if (!formInfo.value.row.details.length) {
    proxy.$message({
      message: `重新发货列表不能为空`,
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  let nameList = dialogTable.value.data
    .filter((item) => item.calcQty <= 0)
    .map((item) => item.factorySubCode)
  if (nameList.length) {
    proxy.$message({
      message: '重新发货列表【' + nameList + '】发货数量必须大于0',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  let list = tableInfo.value.data.filter(
    (item) => item.id !== formInfo.value.oldData.id
  )
  let row = proxy.$fn.deepClone(formInfo.value.row)
  row.details = row.details.concat(list)
  let mergeDetails = proxy.$fn.deepClone(props.tableData)
  mergeDetails[props.tableIndex] = row
  const params = {
    ...props.infoListData,
    mergeDetails: mergeDetails,
  }
  deliverOrderReshipment(params).then((res) => {
    if (res && res.success) {
      handleReClose()
      emits('reset')
      shows.value = false
    }
  })
}
function onCallBackScanData(obj) {
  console.log(obj)
  let info = proxy.$fn.deepClone(props.info)
  let itemIndex = tableInfo.value.data.findIndex(
    (item) =>
      item.factoryMainCode + item.factorySubCode ===
      obj.data.factoryMainCode + obj.data.factorySubCode
  )
  if (itemIndex > -1) {
    proxy.$message({
      message: `重新发货产品不能在原有产品列表中`,
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  if (dialogTable.value.data.length) {
    proxy.$message({
      message: `重新发货列表已有发货产品，请清空后再试`,
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  obj.data.isConsignBusiness = props.infoListData.isConsignBusiness
  let details = dialogTable.value.data
  if (details && details.length) {
    details.forEach((row) => {
      row.isChioce = false
    })
  }
  if (obj.flag === 1) {
    let data = obj.data
    data.flag = true
    data.price = info.price
    data.sterilizationNumber = info.sterilizationNumber
    formInfo.value.data = data
    data.details = [proxy.$fn.deepClone(data)]
    data.factoryMainCode = ''
    data.factorySubCode = ''
    data.gs1Code = ''
    dialogTable.value.data = data.details
    formInfo.value.row = data
    proxy.$message({
      message: `扫码成功`,
      type: 'success',
      duration: 3500,
      showClose: true,
    })
  } else if (obj.flag === 2) {
    let item = proxy.$fn.deepClone(formInfo.value.row)
    let data = obj.data
    data.price = info.price
    data.sterilizationNumber = info.sterilizationNumber
    formInfo.value.data = data
    data.isChioce = true
    item.details.unshift(data)
    item.calcQty = proxy.$fn.accAdd(item.calcQty, data.calcQty || 0)
    item.qty = proxy.$fn.accAdd(item.qty, data.qty || 0)
    item.largeUnitQty = proxy.$fn.accAdd(
      item.largeUnitQty,
      data.largeUnitQty || 0
    )
    item.smallUnitQty = proxy.$fn.accAdd(
      item.smallUnitQty,
      data.smallUnitQty || 0
    )
    item.sumAmount = proxy.$fn.accAdd(
      item.sumAmount,
      proxy.$fn.accDiv(
        proxy.$fn.accMul(data.price || 0, data.calcQty || 0),
        data.unitConvertCoefficient || 1
      )
    )
    dialogTable.value.data = item.details
    formInfo.value.row = item
    proxy.$message({
      message: `扫码成功`,
      type: 'success',
      duration: 3500,
      showClose: true,
    })
  } else if (obj.flag === 3) {
    proxy.$message({
      message: `扫码产品不在当前重新发货范围内`,
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
  }
}
function tableRowClassName({ row = undefined }) {
  if (row.isChioce) {
    return 'success-row'
  } else {
    return ''
  }
}

// 获取列表
function getList() {
  deliverOrderDetailAll(props.query).then((res) => {
    if (res && res.success) {
      tableInfo.value.data = res.data
      tableInfo.value.copyData = tableInfo.value.data
    }
  })
}
function search() {
  const search = filterInfo.value.keyword
  if (search) {
    tableInfo.value.data = tableInfo.value.copyData.filter((data) => {
      return Object.keys(data).some((key) => {
        if (key === 'qrCode') {
          return String(data[key]).indexOf(search) > -1
        } else if (key === 'uniqueCode') {
          return String(data[key]).indexOf(search) > -1
        } else if (key === 'factorySubCode') {
          return String(data[key]).indexOf(search) > -1
        } else if (key === 'factoryMainCode') {
          return String(data[key]).indexOf(search) > -1
        }
      })
    })
  } else {
    tableInfo.value.data = tableInfo.value.copyData
  }
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  proxy.$emit('reset')
}
//打印单个二维码
function printQrCode(row = undefined) {
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else {
    ids = tableInfo.value.data.map((item) => {
      return item.id
    })
  }
  printQrCodeDeliverOrderDetails(ids).then((resp) => {
    if (resp && resp.success) {
      printerInfo.value.visible = true
      printerInfo.value.data = resp.data
    }
  })
}
function printerCallBack(printer) {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.value.data, printer)
  }
  printerInfo.value.visible = false
}
function handleEvent(event, data) {
  switch (event) {
    case 'list':
      tableInfo.value.copyData = data
      break
  }
}

onMounted(() => {
  // hack, 在table创建出来之后再去调用
  proxy.$nextTick(() => {
    getList()
  })
})
</script>

<style scoped lang="scss">
:deep(.filter-item) {
  width: 100%;
}
.text-style {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.scan-groups {
  display: flex !important;
  align-items: center;
}
</style>
